﻿using System;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebScraper
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            SetupUIEnhancements();
        }

        private void SetupUIEnhancements()
        {
            // 文本框内容变化时控制按钮状态
            txtUrl.TextChanged += (s, e) =>
            {
                btnFind.Enabled = !string.IsNullOrWhiteSpace(txtUrl.Text);
            };

            // 右键复制功能
            var menu = new ContextMenuStrip();
            menu.Items.Add("复制", null, (s, e) =>
            {
                var activeList = lstPhoneNumbers.Focused ? lstPhoneNumbers :
                                lstEmails.Focused ? lstEmails : null;
                if (activeList?.SelectedItem != null)
                {
                    Clipboard.SetText(activeList.SelectedItem.ToString());
                }
            });

            lstPhoneNumbers.ContextMenuStrip = menu;
            lstEmails.ContextMenuStrip = menu;
        }

        private async void BtnFind_Click(object sender, EventArgs e)
        {
            string url = txtUrl.Text.Trim();
            if (string.IsNullOrEmpty(url))
            {
                MessageBox.Show("请输入有效的URL！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            btnFind.Enabled = false;
            lstPhoneNumbers.Items.Clear();
            lstEmails.Items.Clear();

            try
            {
                string html = await GetWebContentAsync(url);

                var phones = ExtractPhoneNumbers(html);
                lstPhoneNumbers.Items.AddRange(phones.Length > 0 ? phones : new[] { "未找到电话号码" });

                var emails = ExtractEmails(html);
                lstEmails.Items.AddRange(emails.Length > 0 ? emails : new[] { "未找到邮箱地址" });
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnFind.Enabled = true;
            }
        }

        private async Task<string> GetWebContentAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                // 模拟浏览器请求
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
                return await client.GetStringAsync(url);
            }
        }

        private string[] ExtractPhoneNumbers(string content)
        {
            const string phonePattern = @"(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}";
            var phoneMatches = Regex.Matches(content, phonePattern);
            return phoneMatches.Count > 0
                ? phoneMatches.Cast<Match>().Select(m => m.Value).ToArray()
                : Array.Empty<string>();
        }

        private string[] ExtractEmails(string content)
        {
            const string emailPattern = @"\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}";
            var emailMatches = Regex.Matches(content, emailPattern);
            return emailMatches.Count > 0
                ? emailMatches.Cast<Match>().Select(m => m.Value).ToArray()
                : Array.Empty<string>();
        }
    }
}
